package fr.expdev.bndd;

import java.util.List;

import fr.expdev.bndd.data.Post;
import fr.expdev.bndd.data.PostAdapter;
import fr.expdev.bndd.data.PostsAsyncTask;
import fr.expdev.bndd.R;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;

public class Main extends ListActivity {
	
	private PostAdapter _adapter;
	
	private ImageView _logoImage;
	
	private AppContext appContext = AppContext.getAppContext();
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        appContext.posts.add(new Post("Loading...", "", Post.TYPE_GENERAL));
        
        _adapter = new PostAdapter(this, appContext.posts);
        _logoImage = (ImageView)findViewById(R.id.logo);
        
        setListAdapter(_adapter);
        
        _logoImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				refresh();
			}
		});
        
        refresh();
    }

	@Override
	public void finish() {
		super.finish();
		System.exit(RESULT_OK);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.rssmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			case R.id.menu_refresh:
				refresh();
				return true;
		}
		return false;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent(Main.this, DetailPost.class);
		intent.putExtra("post_number", position);
		startActivity(intent);
	}
    
    private void refresh() {
        _logoImage.setBackgroundResource(R.drawable.loading_animated);
    	((AnimationDrawable)_logoImage.getBackground()).start();
    	PostsAsyncTask task = new PostsAsyncTask(this);
    	task.execute("http://www.experience-developpement.fr/feed/");
    }
	
	public void updatePosts(List<Post> posts) {
		appContext.posts = posts;
		_adapter.setPosts(posts);
		_adapter.notifyDataSetChanged();
		
    	((AnimationDrawable)_logoImage.getBackground()).stop();
        _logoImage.setBackgroundResource(R.drawable.icon);
	}

}